<template>
  <div class="users-container">
    <h2>用户管理</h2>
    
    <div class="users-list">
      <div v-for="user in users" :key="user.username" class="user-item">
        <div class="user-info">
          <img :src="user.avatarUrl || '/default-avatar.png'" class="avatar">
          <div class="user-details">
            <h3>{{ user.username }}</h3>
            <p>注册时间：{{ formatDate(user.registerTime) }}</p>
            <!-- 密码管理部分 -->
            <div class="password-section">
              <span class="password-label">密码：</span>
              <span v-if="!user.isEditing">
                {{ user.showPassword ? user.password : '********' }}
                <button @click="togglePasswordVisibility(user)" class="view-btn">
                  {{ user.showPassword ? '隐藏' : '查看' }}
                </button>
                <button @click="startEdit(user)" class="edit-btn">修改密码</button>
              </span>
              <div v-else class="password-edit">
                <input 
                  type="text" 
                  v-model="user.newPassword" 
                  placeholder="输入新密码"
                >
                <button @click="savePassword(user)" class="save">保存</button>
                <button @click="cancelEdit(user)" class="cancel">取消</button>
              </div>
            </div>
          </div>
        </div>
        
        <div class="user-actions">
          <button 
            v-if="user.username !== 'admin'"
            @click="toggleAdmin(user)" 
            :class="user.isAdmin ? 'remove-admin' : 'make-admin'"
          >
            {{ user.isAdmin ? '取消管理员' : '设为管理员' }}
          </button>
          <button 
            v-if="user.username !== 'admin' && user.username !== currentUser.username"
            @click="deleteUser(user)" 
            class="delete"
          >删除用户</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserManagementComponent',
  data() {
    return {
      users: [],
      currentUser: JSON.parse(localStorage.getItem('currentUser') || '{}')
    }
  },
  created() {
    this.loadUsers()
  },
  methods: {
    loadUsers() {
      this.users = JSON.parse(localStorage.getItem('users') || '[]').map(user => ({
        ...user,
        showPassword: false,
        isEditing: false,
        newPassword: ''
      }))
    },
    formatDate(dateString) {
      return new Date(dateString).toLocaleString()
    },
    togglePasswordVisibility(user) {
      user.showPassword = !user.showPassword
    },
    startEdit(user) {
      user.isEditing = true
      user.newPassword = ''
    },
    cancelEdit(user) {
      user.isEditing = false
      user.newPassword = ''
    },
    savePassword(user) {
      if (!user.newPassword.trim()) {
        alert('密码不能为空')
        return
      }

      // 更新用户密码
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const userIndex = users.findIndex(u => u.username === user.username)
      if (userIndex !== -1) {
        users[userIndex].password = user.newPassword
        localStorage.setItem('users', JSON.stringify(users))
        
        // 如果是当前用户，也更新currentUser
        if (user.username === this.currentUser.username) {
          const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}')
          currentUser.password = user.newPassword
          localStorage.setItem('currentUser', JSON.stringify(currentUser))
        }

        user.password = user.newPassword
        user.isEditing = false
        user.newPassword = ''
        alert('密码修改成功')
      }
    },
    async toggleAdmin(user) {
      if (confirm(`确定要${user.isAdmin ? '取消' : '设为'}管理员吗？`)) {
        const users = this.users.map(u => {
          if (u.username === user.username) {
            return { ...u, isAdmin: !u.isAdmin }
          }
          return u
        })
        
        localStorage.setItem('users', JSON.stringify(users))
        this.users = users

        // 如果是当前登录用户，也更新currentUser
        if (user.username === this.currentUser.username) {
          const updatedUser = { ...this.currentUser, isAdmin: !this.currentUser.isAdmin }
          localStorage.setItem('currentUser', JSON.stringify(updatedUser))
          if (this.$store?.commit) {
            this.$store.commit('updateUser', updatedUser)
          }
        }
      }
    },
    async deleteUser(user) {
      if (confirm('确定要删除该用户吗？此操作不可恢复！')) {
        this.users = this.users.filter(u => u.username !== user.username)
        localStorage.setItem('users', JSON.stringify(this.users))
        
        // 同时删除该用户的管理员申请记录
        const applications = JSON.parse(localStorage.getItem('admin_applications') || '[]')
        const filteredApplications = applications.filter(app => app.username !== user.username)
        localStorage.setItem('admin_applications', JSON.stringify(filteredApplications))
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.users-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;

  .user-item {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .user-info {
      display: flex;
      align-items: center;
      gap: 20px;

      .avatar {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        object-fit: cover;
      }

      .user-details {
        h3 {
          margin-bottom: 5px;
          color: #333;
        }

        p {
          color: #666;
          font-size: 14px;
          margin: 3px 0;
        }

        .password-section {
          margin-top: 10px;
          display: flex;
          align-items: center;
          gap: 10px;

          .password-label {
            color: #666;
          }

          i {
            cursor: pointer;
            margin-left: 5px;
            color: #999;
            
            &:hover {
              color: #666;
            }
          }

          .password-edit {
            display: flex;
            gap: 10px;

            input {
              padding: 4px 8px;
              border: 1px solid #d9d9d9;
              border-radius: 4px;
              
              &:focus {
                outline: none;
                border-color: #40a9ff;
              }
            }

            button {
              padding: 4px 8px;
              border: none;
              border-radius: 4px;
              cursor: pointer;

              &.save {
                background: #52c41a;
                color: white;
                
                &:hover {
                  background: #73d13d;
                }
              }

              &.cancel {
                background: #f5f5f5;
                color: #666;
                
                &:hover {
                  background: #e8e8e8;
                }
              }
            }
          }

          .edit-btn {
            padding: 4px 8px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            
            &:hover {
              background: #40a9ff;
            }
          }
        }
      }
    }

    .user-actions {
      display: flex;
      gap: 10px;

      button {
        padding: 6px 12px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        color: white;

        &.make-admin {
          background: #1890ff;
          &:hover { background: #40a9ff; }
        }

        &.remove-admin {
          background: #faad14;
          &:hover { background: #ffc53d; }
        }

        &.delete {
          background: #ff4d4f;
          &:hover { background: #ff7875; }
        }
      }
    }
  }
}

.password-section {
  .view-btn {
    padding: 4px 8px;
    background: #faad14;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 8px;
    
    &:hover {
      background: #ffc53d;
    }
  }
}
</style> 